package main

import (
	"crypto/tls"
	"log"
	"sync"
)

// BuildTLSConfig builds a tls.Config with SNI-based certificate selection, hot-reloadable.
// Returns nil if no certificates configured.
func BuildTLSConfig(state *State) (*tls.Config, error) {
	certPaths := state.GetCertPaths()
	if len(certPaths) == 0 {
		return nil, nil
	}
	var mu sync.RWMutex
	cache := make(map[string]*tls.Certificate)

	load := func(domain string) *tls.Certificate {
		paths := state.GetCertPaths()
		pair, ok := paths[domain]
		if !ok {
			return nil
		}
		cert, err := tls.LoadX509KeyPair(pair[0], pair[1])
		if err != nil {
			log.Printf("failed to load cert for %s: %v", domain, err)
			return nil
		}
		return &cert
	}

	cfg := &tls.Config{
		MinVersion: tls.VersionTLS12,
		GetCertificate: func(chi *tls.ClientHelloInfo) (*tls.Certificate, error) {
			if chi == nil {
				return nil, nil
			}
			domain := chi.ServerName
			mu.RLock()
			c, ok := cache[domain]
			mu.RUnlock()
			if ok && c != nil {
				return c, nil
			}
			// lazy load/update
			cert := load(domain)
			if cert == nil {
				return nil, nil
			}
			mu.Lock()
			cache[domain] = cert
			mu.Unlock()
			return cert, nil
		},
	}
	return cfg, nil
}
